package nkr1pt.popkorn.helper;

import java.io.File;
import java.io.IOException;
import nkr1pt.popkorn.exceptions.RecoverableException;
import org.apache.commons.io.FilenameUtils;

/**
 * Provides utilities for working with files.
 *
 * @author Kristof Vanhaeren
 */
public class FileUtils {

    public static File createFile(String fileName) {
        File outputFile = null;
        File dir = new File(FilenameUtils.getFullPath(fileName));
        if (dir.exists()) {
            outputFile = new File(fileName);
        } else {
            if (new File(FilenameUtils.getFullPath(fileName)).mkdirs()) {
                outputFile = new File(fileName);
            }
        }

        return outputFile;
    }

    public static void moveFileToDirectory(File file, File location) {
        try {
            org.apache.commons.io.FileUtils.moveFileToDirectory(file, location, true);
        } catch (IOException ex) {
            throw new RecoverableException(ex.getMessage());
        }
    }

    public static void moveDirectoryToDirectory(File source, File dest) {
        try {
            org.apache.commons.io.FileUtils.moveDirectoryToDirectory(source, dest, true);
        } catch (IOException ex) {
            throw new RecoverableException(ex.getMessage());
        }
    }

    public static boolean removeFile(File file) {
        return file.delete();
    }

    public static boolean isAccessable(File file) {
        return file.exists() && file.canRead();
    }

    public static String getExtension(File file) {
        String filename = file.getName();
        String extension = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length());
        return extension;
    }

}